﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Musicman.Utilities;
using Musicman.Utilities.Configuration;
using Musicman.Common;
using System.Collections;
using Musicman.Utilities.Configuration.Search;
using Musicman.Business;
using System.Net.Mail;
using System.IO;

namespace MusicmanTest
{
    public partial class Form1 : Form
    {
        private SearchJobsConfigurationSection myJobs;
        
        FileFinder fileFinder = new FileFinder();
        Hashtable progresses = new Hashtable();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            myJobs = (SearchJobsConfigurationSection)AppSettingsHelper.GetWebConfigSection(Constants.SearchJobsSection);
            fileFinder.ProgressChanged += new FileFindProgerssEventHandler(fileFinder_ProgressChanged);
            fileFinder.FileFindCompleted += new FileFindCompletedEventHandler(fileFinder_FileFindCompleted);
            fileFinder.Error += new Musicman.Utilities.ErrorEventHandler(fileFinder_Error);

            SearchScheduler.Instance.ProgressChanged += new SearchJobProgerssEventHandler(Search_ProgressChanged);
            SearchScheduler.Instance.SearchJobCompleted += new SearchJobCompletedEventHandler(Search_SearchJobCompleted);
            SearchScheduler.Instance.Error += new Musicman.Utilities.ErrorEventHandler(Instance_Error);
        }

        void Instance_Error(FileFindErrorEventArgs e)
        {
            if (textBox1.InvokeRequired)
            {
                Musicman.Utilities.ErrorEventHandler d = new Musicman.Utilities.ErrorEventHandler(Instance_Error);
                this.Invoke(d, e);
            }
            else
            {
                textBox1.AppendText(String.Format("error occured: {0}, {1} \r\n",
                    e.Description, e.Exception.Message));
            }
        }

        void Search_SearchJobCompleted(object sender, SearchJobCompletedEventArgs e)
        {
            if (textBox1.InvokeRequired)
            {
                SearchJobCompletedEventHandler d = new SearchJobCompletedEventHandler(Search_SearchJobCompleted);
                this.Invoke(d, sender, e);
            }
            else
            {
                TimeSpan sTime = new TimeSpan(e.SearchTime);
                TimeSpan pTime = new TimeSpan(e.Processtime);
                textBox1.AppendText(String.Format("taskid: {0}, filesFound: {1} filesAdded: {2}, filesDeleted: {3}, searchTime: {4}, processtime: {5} \r\n",
                    e.UserState, e.FilesFound, e.FilesAdded, e.FilesDeleted, sTime, pTime));
            }
            
        }

        void Search_ProgressChanged(SearchJobProgerssChangedEventArgs e)
        {
            if (textBox1.InvokeRequired)
            {
                SearchJobProgerssEventHandler d = new SearchJobProgerssEventHandler(Search_ProgressChanged);
                this.Invoke(d, e);
            }
            else
            {
                textBox1.AppendText(String.Format("taskid: {0}, taskpercentage: {1} \r\n",
                    e.UserState, e.ProgressPercentage));
                if (progresses[e.UserState] == null)
                {
                    ProgressBar pb = new ProgressBar();
                    progresses[e.UserState] = pb;

                    pb.Maximum = 100;
                    pb.Location = new Point(0, 70 + progresses.Count * 30);
                    tabPage1.Controls.Add(pb);
                }
                ((ProgressBar)progresses[e.UserState]).Value = e.ProgressPercentage;
            }
            // throw new NotImplementedException();
        }

        void fileFinder_ProgressChanged(FileFindProgerssChangedEventArgs e)
        {
            if (textBox1.InvokeRequired)
            {
                FileFindProgerssEventHandler d = new FileFindProgerssEventHandler(fileFinder_ProgressChanged);
                this.Invoke(d, e);
            }
            else
            {
                textBox1.AppendText(String.Format("taskid: {0} taskstatus: {1}, taskpercentage: {2}, files: {3} elapsedtime: {4} currlocation: {5} \r\n",
                    e.UserState, e.Status, e.ProgressPercentage, e.Files != null ? e.Files.Length : 0, e.ElapsedTime, e.SearchLocation));
                if (progresses[e.UserState] == null)
                {
                    ProgressBar pb = new ProgressBar();
                    progresses[e.UserState] = pb;

                    pb.Maximum = 100;
                    pb.Location = new Point(0, 70 + progresses.Count * 30);
                    tabPage1.Controls.Add(pb);
                }
                ((ProgressBar)progresses[e.UserState]).Value = e.ProgressPercentage;
            }
        }

        void fileFinder_Error(FileFindErrorEventArgs e)
        {
            if (textBox1.InvokeRequired)
            {
                Musicman.Utilities.ErrorEventHandler d = new Musicman.Utilities.ErrorEventHandler(fileFinder_Error);
                this.Invoke(d, e);
            }
            else
            {
                textBox1.AppendText(String.Format("error: {0} \r\n", e.Description));
            }
        }

        void fileFinder_FileFindCompleted(object sender, FileFindCompletedEventArgs e)
        {
            if (textBox1.InvokeRequired)
            {
                FileFindCompletedEventHandler d = new FileFindCompletedEventHandler(fileFinder_FileFindCompleted);
                this.Invoke(d, sender, e);
            }
            else
            {
                textBox1.AppendText(String.Format("taskid: {0} canceled: {1} totalfiles: {2} totaltime: {3} \r\n",
                    e.UserState, e.Cancelled, e.TotalFiles, new TimeSpan(e.EndTime.Ticks - e.StartTime.Ticks)));
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < myJobs.SearchJobs.Count; i++)
            {
                SearchJobConfigurationElement searchJob = (SearchJobConfigurationElement)myJobs.SearchJobs[i];
                fileFinder.SearchFilesAsync(
                    searchJob,
                    myJobs.SearchLocations.ToStringList(),
                    searchJob.Name);

                ProgressBar pb = new ProgressBar();
                progresses[searchJob.Name] = pb;

                pb.Maximum = 100;
                pb.Location = new Point(0, 100 + i * 30);
                tabPage1.Controls.Add(pb);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // SearchScheduler.Instance.StartCron();
            SearchScheduler.Instance.RunSearchTask(SearchMode.JobsAtOnce);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            long jobId = 0;
            if (Int64.TryParse(txtJobID.Text, out jobId))
            {
                SearchFileManager.Instance.SetVisited(jobId, cbSetVisited.Checked);
            }
            else
            {
                MessageBox.Show("Invalid jobID");
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            long jobId = 0;
            int deleteAfter = 0;
            if (Int64.TryParse(txtJobid2.Text, out jobId) && Int32.TryParse(txtDeleteAfterSeq.Text, out deleteAfter))
            {
                SearchFileManager.Instance.IncreaseAndDeleteNonVisitedFiles(jobId, deleteAfter);
            }
            else
            {
                MessageBox.Show("Invalid jobID or delete after");
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (MailSender.Instance != null)
            {
                MailMessage email = new MailMessage();
                email.From = new MailAddress("musicmanservices@musicman.com");
                email.To.Add(new MailAddress(txtMailTo.Text));
                email.Subject = txtSubject.Text;
                email.Body = txtMail.Text;
                email.IsBodyHtml = false;
                MailSender.Instance.SendMail(email);

            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            SearchScheduler.Instance.StopCron();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            SearchScheduler.Instance.StopSearchTask();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                txtFilePath.Text = openFileDialog1.FileName;
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            long userId = 0;
            if (Int64.TryParse(txtUserID.Text, out userId) && File.Exists(txtFilePath.Text))
            {
                byte [] imageData = null;
                using (FileStream fs = File.Open(txtFilePath.Text, FileMode.Open, FileAccess.Read))
                {
                    imageData = new byte[fs.Length];
                    fs.Read(imageData, 0, imageData.Length);
                }
                UserManager.Instance.UpdateProfilePicture(userId, imageData);
            }
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            long userId = 0;
            if (Int64.TryParse(txtUserId2.Text, out userId))
            {
                byte[] imageData = UserManager.Instance.LoadProfilePicture(userId);
                MemoryStream ms = new MemoryStream(imageData);
                pictureBox1.Image = Image.FromStream(ms);
                ms.Close();
            }
        }
        
    }
}
